package com.huangsiyuan.myepidemic;


import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.DataSourceConnectionFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(basePackages = "com.huangsiyuan.myepidemic.mapper")
public class MyBatisConfig {

    private static Logger logger= Logger.getLogger(MyBatisConfig.class);

    //配置數據源
    @Bean(name = "dataSource",destroyMethod = "close")
    public BasicDataSource basicDataSource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/epidemic");
        dataSource.setUsername("root");
        dataSource.setPassword("&Huang123.456");
        dataSource.setInitialSize(3);
        dataSource.setMaxActive(50);
        dataSource.setMaxIdle(1);
        dataSource.setMaxWait(4000);
        dataSource.setDefaultAutoCommit(false);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        //設置要使用的數據源
        factoryBean.setDataSource(dataSource);

        SqlSessionFactory factory=null;

        //設置xml文件中的類所在的包
        factoryBean.setTypeAliasesPackage("com.huangsiyuan.myepidemic.beans");

        //爲了讓mybatis自動將下劃綫分割的列名轉換為駝峰表示的屬性名
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);

        try {
            //設置映射xml文件的路徑
            Resource[] resources=new PathMatchingResourcePatternResolver().getResources("classpath:com/huangsiyuan/myepidemic/mapper/*Mapper.xml");
            factoryBean.setMapperLocations(resources);
            factory=factoryBean.getObject();
        } catch (Exception e) {
            logger.error("解析映射xml文件時異常："+e.getMessage());
        }

        return factory;
}
}


